package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMMatch;
import com.shwread.android.qysw.step.dto.HMMatchsDto;
import com.shwread.android.qysw.step.dto.LqswHealthMatch;
import com.shwread.android.qysw.step.dto.Player;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.RectImageView;
import com.shwread.android.qysw.tools.TimeHelper;
import com.shwread.android.qysw10000182.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/4/9.
 */
public class FriendPKNewActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.date_pk_text)
    TextView datePkText;
    @InjectView(R.id.date_time_text)
    TextView dateTimeText;
    @InjectView(R.id.top_layout)
    LinearLayout topLayout;
    @InjectView(R.id.today_layout)
    LinearLayout todayLayout;
    @InjectView(R.id.sec_date_time_text)
    TextView secDateTimeText;
    @InjectView(R.id.sec_layout)
    LinearLayout secLayout;
    @InjectView(R.id.tomorrow_layout)
    LinearLayout tomorrowLayout;
    @InjectView(R.id.no_firend_game_layout)
    RelativeLayout noFirendGameLayout;
    @InjectView(R.id.create_game_button)
    RelativeLayout createGameButton;
    @InjectView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    TimerTask task;
    Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.h_friend_pk_new_activity);
        ButterKnife.inject(this);
        topLayout.setVisibility(View.GONE);
        secLayout.setVisibility(View.GONE);
        titleText.setText("友谊赛");
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rightText.setVisibility(View.VISIBLE);
        rightText.setText("历史记录");
        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FriendPKNewActivity.this, FriendPKHistoryActivity.class);
                startActivity(intent);
            }
        });
        createGameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FriendPKNewActivity.this, HealthyChooseFriendActivity.class);
                intent.putExtra("matchName", "J好友PK");
                intent.putExtra("matchException", "J好友PK");
                intent.putExtra("startTime", "");
                intent.putExtra("endTime", "");
                intent.putExtra("targetStep", "1000");
                intent.putExtra("gameType", "1");
                startActivity(intent);
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(false);
                refresh();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    private void refresh() {
        todayLayout.removeAllViews();
        tomorrowLayout.removeAllViews();
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        params.put("page", "1");
        params.put("pageSize", "500");
        params.put("isCreater", "2");
        params.put("type", "1");
        String unstartUrl = "/hzlqswserver/health/game/unStart";
        HashMap<String, String> hashMapUrl2 = new HashMap<>();
        hashMapUrl2.put("url", unstartUrl);
        MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("returnObject");
                    Log.i("darren2", res);

                    if (TextUtils.isEmpty(res)) {
                        noFirendGameLayout.setVisibility(View.VISIBLE);
                    } else {
                        noFirendGameLayout.setVisibility(View.INVISIBLE);

                        HMMatchsDto hmMatchsDto = HMMatchsDto.parserJson(res);
                        List<HMMatch> hmMatches = hmMatchsDto.getHMMatchs();

                        if (hmMatches == null || hmMatches.size() == 0) {
                            noFirendGameLayout.setVisibility(View.VISIBLE);
                        }
                        for (int i = 0; i < hmMatches.size(); i++) {

                            final HMMatch hmMatch = hmMatches.get(i);
                            final LqswHealthMatch lqswHealthMatch = hmMatch.getLqswHealthMatch();
                            int ownerId = lqswHealthMatch.getOwnerId();
                            int state = hmMatch.getLqswHealthMatch().getState();
                            List<Player> players = hmMatch.getPlayers();
                            if (TimeHelper.isToday(lqswHealthMatch.getStartTime())) {
                                topLayout.setVisibility(View.VISIBLE);
                                task = new TimerTask() {
                                    @Override
                                    public void run() {

                                        runOnUiThread(new Runnable() {      // UI thread
                                            @Override
                                            public void run() {
                                                dateTimeText.setText("距离结束还有" + TimeHelper.getMyFriendCountDownTime(TimeHelper.getTodayPKEnd()));
                                            }
                                        });
                                    }
                                };
                                timer.schedule(task, 1000, 1000);

                                View view = View.inflate(FriendPKNewActivity.this, R.layout.h_pk_friend_item, null);
                                ViewHolder viewHolder = new ViewHolder(view);
                                for (int j = 0; j < players.size(); j++) {
                                    if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                        if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                            viewHolder.leftNameText.setText("我");
                                        } else {
                                            viewHolder.leftNameText.setText(players.get(j).getNickName());
                                        }

                                        if (!TextUtils.isEmpty(players.get(j).getUserHead())) {
                                            Picasso.with(FriendPKNewActivity.this).load(players.get(j).getUserHead()).into(viewHolder.leftHeadIconImg);
                                        }
                                    } else {
                                        if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                            viewHolder.rightNameText.setText("我");
                                        } else {
                                            viewHolder.rightNameText.setText(players.get(j).getNickName());
                                        }

                                        if (!TextUtils.isEmpty(players.get(j).getUserHead())) {
                                            Picasso.with(FriendPKNewActivity.this).load(players.get(j).getUserHead()).into(viewHolder.rightHeadIconImg);
                                        }
                                    }
                                }

                                int judge = 0;
                                int myState = 0;
                                for (int k = 0; k < players.size(); k++) {
                                    if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                                        myState = 1;
                                    }
                                    if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {

                                        judge = 1;
                                    }
                                }
                                //int state = hmMatch.getLqswHealthMatch().getState();//(1),未开始，(2)开始，(3)结束，(4)失效
                                viewHolder.centerText.setTextColor(FriendPKNewActivity.this.getResources().getColor(R.color.white));
                                if (judge == 1) {//好友未接受
                                    viewHolder.centerText.setText("等待对方接受PK");
                                } else if (myState == 1) {
                                    viewHolder.centerText.setText("点击接受比赛");
                                } else if (judge == 0 && myState == 0) {
                                    viewHolder.centerText.setText("比赛进行中");
                                }

                                viewHolder.pkItemLayout.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                            Intent intent = new Intent(FriendPKNewActivity.this, FriendPKDetailActivity.class);
                                            Bundle bundle = new Bundle();
                                            bundle.putSerializable("hmMatch", hmMatch);
                                            intent.putExtras(bundle);
                                            FriendPKNewActivity.this.startActivity(intent);
                                    }
                                });
                                todayLayout.addView(view);
                            }

                        }
                        for (int i = 0; i < hmMatches.size(); i++) {
                            final HMMatch hmMatch = hmMatches.get(i);
                            final LqswHealthMatch lqswHealthMatch = hmMatch.getLqswHealthMatch();
                            int ownerId = lqswHealthMatch.getOwnerId();
                            int state = hmMatch.getLqswHealthMatch().getState();
                            List<Player> players = hmMatch.getPlayers();
                            if (!TimeHelper.isToday(lqswHealthMatch.getStartTime())) {
                                secLayout.setVisibility(View.VISIBLE);
                                View view = View.inflate(FriendPKNewActivity.this, R.layout.h_pk_friend_item, null);
                                ViewHolder viewHolder = new ViewHolder(view);
                                for (int j = 0; j < players.size(); j++) {

                                    task = new TimerTask() {
                                        @Override
                                        public void run() {

                                            runOnUiThread(new Runnable() {      // UI thread
                                                @Override
                                                public void run() {
                                                    secDateTimeText.setText("距离结束还有" + TimeHelper.getMyFriendCountDownTime(TimeHelper.getTomorrowPKEnd()));
                                                }
                                            });
                                        }
                                    };
                                    timer.schedule(task, 1000, 1000);
                                    if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                        if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                            viewHolder.leftNameText.setText("我");
                                        } else {
                                            viewHolder.leftNameText.setText(players.get(j).getNickName());
                                        }

                                        if (!TextUtils.isEmpty(players.get(j).getUserHead())) {
                                            Picasso.with(FriendPKNewActivity.this).load(players.get(j).getUserHead()).into(viewHolder.leftHeadIconImg);
                                        }
                                    } else {
                                        if (UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() == players.get(j).getUserId()) {
                                            viewHolder.rightNameText.setText("我");
                                        } else {
                                            viewHolder.rightNameText.setText(players.get(j).getNickName());
                                        }

                                        if (!TextUtils.isEmpty(players.get(j).getUserHead())) {
                                            Picasso.with(FriendPKNewActivity.this).load(players.get(j).getUserHead()).into(viewHolder.rightHeadIconImg);
                                        }
                                    }
                                }

                                int judge = 0;
                                int myState = 0;
                                for (int k = 0; k < players.size(); k++) {
                                    if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                                        myState = 1;
                                    }
                                    if (players.get(k).getIsAccept() == 0 && players.get(k).getUserId() != UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {

                                        judge = 1;
                                    }
                                }
                                //int state = hmMatch.getLqswHealthMatch().getState();//(1),未开始，(2)开始，(3)结束，(4)失效
                                viewHolder.centerText.setTextColor(FriendPKNewActivity.this.getResources().getColor(R.color.white));
                                if (judge == 1) {//好友未接受
                                    viewHolder.centerText.setText("等待对方明日接受PK");
                                } else if (myState == 1) {
                                    viewHolder.centerText.setText("点击接受比赛");
                                } else if (judge == 0 && myState == 0) {
                                    viewHolder.centerText.setText("明日开启");
                                }


                                viewHolder.pkItemLayout.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(FriendPKNewActivity.this, FriendPKDetailActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("hmMatch", hmMatch);
                                        intent.putExtras(bundle);
                                        FriendPKNewActivity.this.startActivity(intent);
                                    }
                                });
                                tomorrowLayout.addView(view);
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        asynctask.execute(hashMapUrl2, params);
    }

    static class ViewHolder {
        @InjectView(R.id.left_head_icon_img)
        RectImageView leftHeadIconImg;
        @InjectView(R.id.center_text)
        TextView centerText;
        @InjectView(R.id.left_step)
        TextView leftStep;
        @InjectView(R.id.right_step)
        TextView rightStep;
        @InjectView(R.id.step_layout)
        LinearLayout stepLayout;
        @InjectView(R.id.result_img)
        ImageView resultImg;
        @InjectView(R.id.right_head_icon_img)
        RectImageView rightHeadIconImg;
        @InjectView(R.id.pk_item_layout)
        FrameLayout pkItemLayout;
        @InjectView(R.id.left_name_text)
        TextView leftNameText;
        @InjectView(R.id.right_name_text)
        TextView rightNameText;
        @InjectView(R.id.bottom_layout)
        LinearLayout bottomLayout;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}
